package com.digitalchina.lxnsy.activity.old;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessLecturer;
import com.digitalchina.lxnsy.api.BusinessTraining;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.AttentionTeacherVO;
import com.digitalchina.lxnsy.entity.TrainVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.LecturerTrainHolder;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hedgehog.ratingbar.RatingBar;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

import static com.digitalchina.lxnsy.R.id.headview_lecturer_iv_lecturer_head;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：讲师详情
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/3/23 15:14:45
 * 修改备注：
 * ================================================
 */

public class LecturerDetailActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    @Bind(R.id.activity_lecturer_detail_recycler_view)
    EasyRecyclerView recyclerView;


    private View headView;//头布局
    private TextView tvLecturerName;//讲师姓名
    private TextView tvLecturerTitle;//讲师职称
    private TextView tvWorkPlace;//工作单位
    private RatingBar barScore;//讲师评分
    private TextView tvField;//涉及领域
    private TextView tvGrade;//评分
    private SimpleDraweeView ivLecturerHead;//讲师头像
    private RelativeLayout rlFollow;//关注Ta
    private TextView tvFollow;//关注Ta


    private RecyclerArrayAdapter adapter;
    private int page = 1;
    private int num = 10;

    private List<TrainVO> trainList = new ArrayList<>();

    private AttentionTeacherVO lecturerVo;//讲师

    private String lecturerId;//讲师ID

    private boolean isAttend = true;//是否关注

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_lecturer_detail);
        setTitle("讲师详情");
    }

    @Override
    public void initMember() {

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
//        recyclerView.addItemDecoration(Utils.setSpaceDecoration(this, false, true, false));

        recyclerView.setAdapter(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new LecturerTrainHolder(parent);
            }
        });


        lecturerVo = (AttentionTeacherVO) getIntent().getSerializableExtra("AttentionTeacherVO");

        headView = LayoutInflater.from(LecturerDetailActivity.this).inflate(R.layout.view_headview_lecturer_detail, null);


        tvLecturerName = (TextView) headView.findViewById(R.id.headview_lecturer_tv_name);
        tvLecturerTitle = (TextView) headView.findViewById(R.id.headview_lecturer_tv_title); // 职务
        tvWorkPlace = (TextView) headView.findViewById(R.id.headview_lecturer_tv_work_place); // 工作单位
//        barScore = (RatingBar) headView.findViewById(R.id.headview_lecturer_bar_score);
        tvField = (TextView) headView.findViewById(R.id.headview_lecturer_tv_field); // 从事专业
        tvGrade = (TextView) headView.findViewById(R.id.headview_lecturer_tv_grade); // 评分
        ivLecturerHead = (SimpleDraweeView) headView.findViewById(headview_lecturer_iv_lecturer_head);
        rlFollow = (RelativeLayout) headView.findViewById(R.id.headview_lecturer_rl_lecturer_follow);
        tvFollow = (TextView) headView.findViewById(R.id.headview_lecturer_tv_lecturer_follow);


        adapter.addHeader(new RecyclerArrayAdapter.ItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {

                return headView;
            }

            @Override
            public void onBindView(View headerView) {


            }
        });


        if (lecturerVo == null) {
            showToast("获取信息异常");
            return;
        }
        lecturerId = lecturerVo.getAgriTeacher().getId();

        onRefresh();
        setLecturerInfo();
        changeAttendStatus();
//        setData();
    }

    @Override
    public void addListener() {
        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        rlFollow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO 关注与取消关注
                if (Utils.isLogin(LecturerDetailActivity.this)) {
                    if (!StringUtil.isStrEmpty(lecturerId))
                        BusinessTraining.toAddAttention(LecturerDetailActivity.this, lecturerId, "", mHandler);
                }
            }
        });

        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                back();
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);

                switch (msg.what) {
                    case MSG.MSG_GET_LECTURER_TRAIN_LIST_SUCCESS://讲师培训
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_LECTURER_TRAIN_LIST_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        break;
                    case MSG.MSG_TO_ADD_ATTENTION_SUCCESS: // 关注
                        if (isAttend) {
                            isAttend = false;
                            changeAttendStatus();
                        } else {
                            isAttend = true;
                            changeAttendStatus();
                        }
                        break;
                    case MSG.MSG_TO_ADD_ATTENTION_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    /**
     * 更改关注按钮的状态
     */
    private void changeAttendStatus() {
        if (isAttend) { // 已关注
            rlFollow.setBackgroundResource(R.drawable.shape_already_attend);
            tvFollow.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.bd_ic_check_mark), null, null, null);
            tvFollow.setText("已关注");
            tvFollow.setTextColor(Color.parseColor("#B3B3B3"));
        } else {
            rlFollow.setBackgroundResource(R.drawable.shape_headview_lecturer_follow);
            tvFollow.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_headview_lecturer_add_follows), null, null, null);
            tvFollow.setText("关注");
            tvFollow.setTextColor(getResources().getColor(R.color.app_color));
        }
    }

    @Override
    public void callBack(Object object) {
        trainList = FastJsonUtil.getListBean(object.toString(), "body", "agriTrainings", TrainVO.class);
        if (trainList == null)
            return;
        if (page == 1) { // 刷新
            adapter.clear();
        }

        if (trainList != null) {
            if (trainList.size() < num) {
                adapter.stopMore();
            }
        }

        adapter.addAll(trainList);
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public void onRefresh() {
        page = 1;
        BusinessLecturer.getLecturerTrainList(this, lecturerId, String.valueOf(page), String.valueOf(num), mHandler);
    }

    @Override
    public void onLoadMore() {
        //没有分页
            page++;
            BusinessLecturer.getLecturerTrainList(this, lecturerId, String.valueOf(page), String.valueOf(num), mHandler);
    }

    public void setLecturerInfo() {

        AttentionTeacherVO.AgriTeacherBean teacherBean = lecturerVo.getAgriTeacher();

        tvLecturerName.setText(teacherBean.getName());
        tvLecturerTitle.setText(teacherBean.getTitle());
        tvWorkPlace.setText(teacherBean.getWorkUnit()); // 工作单位
//        if (!TextUtils.isEmpty(teacherBean.getTrainScore().toString())) {
//            String score = teacherBean.getTrainScore().toString();
//            barScore.setStar(Float.parseFloat(score));
//        }

//        barScore.halfStar(true);
        tvField.setText(teacherBean.getProfession()); // 从事专业 需要修改
        FrescoUtil.showImageSmall(teacherBean.getImg(), ivLecturerHead);

        if (!StringUtil.isStrEmpty(teacherBean.getTrainScore())) { // 判断评分对应的等级
            int score = (int) (Double.valueOf(teacherBean.getTrainScore()).doubleValue());
            if ( score< 36)
                tvGrade.setText("差");
            else if (score < 42)
                tvGrade.setText("中");
            else if (score < 48)
                tvGrade.setText("良");
            else if (score < 60)
                tvGrade.setText("优");
        } else
            tvGrade.setText("暂无"); // TODO 评分
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void back() {
        if (!isAttend) {
            setResult(1);
        }
        finish();
    }


}
